<template>
  <div class="main_content role">
    <father-title :title="fatherTitle"></father-title>
    <div class="contentBox content">
      <div class="box">
        <div class="perms">
          <div class="item">
            <div class="header">菜单权限</div>
            <div class="tree">
              <Tree ref="menu" :data="permsMenuList" show-checkbox check-directly></Tree>
            </div>
          </div>
          <div class="item">
            <div class="header">数据权限</div>
            <div class="tree">
              <Tree ref="dept" :data="permsDeptList" show-checkbox check-strictly check-directly></Tree>
            </div>
          </div>
        </div>

        <div class="form">
          <div class="header">
            <div class="line"></div>
            <div class="title">{{headerTitle}}</div>
          </div>
          <Form
              class="form"
              ref="form"
              :model="formValidate"
              :rules="ruleValidate"
              label-position="top"
              slot="content">
            <FormItem label="角色名称" prop="roleName">
              <Input v-model="formValidate.roleName" placeholder="请输入角色名称" />
            </FormItem>
            <FormItem label="所属部门" prop="dept">
              <Cascader
                  :data="deptList"
                  v-model="formValidate.dept"
                  change-on-select
                  filterable
                  placeholder="请选择部门"
                  @on-change="changeDept"></Cascader>
            </FormItem>
            <FormItem label="备注" prop="remark">
              <Input v-model="formValidate.remark" placeholder="角色备注" />
            </FormItem>
          </Form>
          <div>
            <Button :loading="loading" style="width: 80px;margin-top: 10px" type="primary" @click="addOrEditData">提交</Button>
            <Button style="width: 80px;margin-top: 10px; margin-left: 10px" @click="back">返回</Button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {formValidate, ruleValidate} from "./pageConfig";
import axios from "axios";

export default {
  name: 'AddOrEditRole',

  data() {
    return {
      formValidate: {...formValidate},
      ruleValidate,
      fatherTitle: "",
      headerTitle: "",
      deptList: [],
      permsDeptList: [],
      permsMenuList: [],
      loading: false,
    };
  },

  mounted() {
    if(this.$route.params.type_id === 'add'){
      this.fatherTitle = "新增角色";
      this.headerTitle = "新增";
    }else{
      this.fatherTitle = "修改角色";
      this.headerTitle = "修改";
    }
    // 获取列表信息
    this.getAllList();
  },

  computed: {},

  methods: {
    treeChecked(tree, checked, map, isSelectFather){
      let _tree = JSON.parse(JSON.stringify(tree));
      _tree.forEach((item)=>{
        // 判断是否有下级，如果有下级就继续循环
        if(item[map.children] && item[map.children].length > 0){
          if(checked.includes(item[map.compare]) && isSelectFather){
            item.checked = checked.includes(item[map.compare]);
          }else{
            item.checked = false;
          }
          item[map.children] = this.treeChecked(item[map.children], checked, map, isSelectFather);
        }else{
          item.checked = checked.includes(item[map.compare]);
        }
      });
      return _tree;
    },
    // 获取角色信息
    getRoleInfo(){
      this.$api.get('sp/sys/role/info/' + this.$route.params.type_id).then((res)=>{
        if(res.data.code === 0){
          this.formValidate = {...res.data.role};
          // 通过查找树遍历出节点路径
          this.formValidate.dept = this.$utils.util.findLeafPathInTree(this.deptList, this.formValidate.deptId, {
            value: "value",
            children: "children",
            compare: "deptId",
          });

          // 数据权限树回显
          this.permsDeptList = this.$utils.util.treeChecked(this.permsDeptList, res.data.role.deptIdList, {
            children: "children",
            compare: "deptId",
          }, true);

          // 菜单权限树回显
          this.permsMenuList = this.$utils.util.treeChecked(this.permsMenuList, res.data.role.menuIdList, {
            children: "children",
            compare: "menuId",
          }, false);
        }
      });
    },

    // 返回
    back(){
      this.$router.back();
    },

    // 新增或修改
    addOrEditData(){
      this.formValidate.deptIdList = this.$refs.dept.getCheckedAndIndeterminateNodes().map((item)=>item.deptId);
      this.formValidate.menuIdList = this.$refs.menu.getCheckedAndIndeterminateNodes().map((item)=>item.menuId);
      // 校验数据
      this.$refs.form.validate(state => {
        if (!state){
          return this.$Message.warning("请填写对应的值");
        }
        this.loading = true;
        // 判断新增或修改
        if(this.$route.params.type_id !== 'add'){
          this.$api.post('sp/sys/role/update', this.formValidate).then((res)=>{
            if(res.data.code === 0){
              this.$Message.success("修改成功");
              this.back();
            }
          }).finally(()=> this.loading = false);
        }else{
          this.$api.post('sp/sys/role/save', this.formValidate).then((res)=>{
            if(res.data.code === 0){
              this.$Message.success("新增成功");
              this.back();
            }
          }).finally(()=> this.loading = false);
        }
      });
    },

    // 改变所属部门
    changeDept(value, selectValue){
      // 设置参数
      if(!this.$utils.util.isEqualsNull(selectValue)){
        this.formValidate.deptId = selectValue[selectValue.length -1].deptId;
        // 数据权限树回显
        this.$nextTick(()=>{
          this.permsDeptList = this.$utils.util.treeChecked(this.permsDeptList, [this.formValidate.deptId], {
            children: "children",
            compare: "deptId",
          }, true);
        });
        this.formValidate.deptName = selectValue[selectValue.length -1].name;
      }else{
        this.formValidate.deptId = null;
        this.formValidate.deptName = null;
      }
    },

    // 并发发起请求
    getAllList(){
      axios.all([this.getDeptList(), this.getMenuList()]).then((axios.spread((dept, menu)=>{
        if(dept.data.code === 0){
          // 组装级联数据
          this.deptList = this.$utils.util.convertCascaderList(dept.data.data, {
            value: 'deptId',
            label: 'name',
            children: 'children',
          });

          // 重新组装数据
          this.permsDeptList = dept.data.data.map(p => {
            let item = this.parseChildren(p, {
              expand: true,
              disableCheckbox: true,
              disabled: true,
            });
            item.expand = true;
            item.disableCheckbox = true;
            item.disabled = true;
            return item;
          });
        }
        // 菜单数据
        if(menu.data.code === 0){
          // 重新组装数据
          this.permsMenuList = menu.data.data.map(p => {
            let item = this.parseChildren(p, {
              expand: true,
            });
            item.expand = true;
            return item;
          });
        }
        // 判断是否为修改
        if(dept.data.code === 0 && menu.data.code === 0 && this.$route.params.type_id !== 'add'){
          this.getRoleInfo();
        }
      })));
    },

    // 获取部门数据
    getDeptList(){
      return this.$api.get('sp/sys/dept/list');
    },

    // 获取菜单列表
    getMenuList(){
      return this.$api.get("sp/sys/menu/list");
    },

    // 组装数据
    parseChildren(node, map) {
      return {
        ...node,
        ...map,
        title: node.name,
        children: node.children !== null ? node.children.map(_node => this.parseChildren(_node, map)) : [],
      };
    },
  }
};
</script>

<style scoped lang="less">
  .role {
    > .content{
      overflow-y: scroll;
      > .box{
        display: flex;
        flex: 1;
        padding: 20px;
        overflow: hidden;
        > .form{
          display: flex;
          flex: 1;
          flex-direction: column;
          padding-left: 20px;
          > .header{
            display: flex;
            height: 44px;
            align-items: center;
            border-bottom: 1px solid #e8eaec;
            margin-bottom: 20px;
            > .line{
              width: 6px;
              height: 16px;
              margin-right: 8px;
              background: #285EE2;
              border-radius: 3px;
            }
            > .title{
              color: #333333;
              font-size: 16px;
            }
          }
        }

        // 权限菜单样式
        > .perms{
          display: flex;
          width: 740px;
          overflow: hidden;
          > .item{
            display: flex;
            flex-direction: column;
            flex: 1;
            width: 360px;
            margin-left: 20px;
            > .header{
              height: 44px;
              border-radius: 6px 6px 0 0;
              background: #4a9bff;
              color: white;
              text-align: center;
              line-height: 44px;
              font-size: 16px;
            }
            > .tree{
              display: flex;
              flex: 1;
              flex-direction: column;
              background: #f5f6f6;
              border: 1px solid #e1e3eb;
              border-radius: 0 0 6px 6px;
              overflow-y: scroll;
              border-top: none;
              padding: 10px 10px;
            }
          }
          > .item:first-child{
            margin-left: 0;
          }
        }
      }

    }
  }
</style>